import Cache from '@/utils/cache';
import {
    UID,
    USER_INFO,
    LOGIN_STATUS,
} from '@/config/cache';

const state = {
    token: Cache.get(LOGIN_STATUS) || '',
    userInfo: Cache.get(USER_INFO) ? JSON.parse(Cache.get(USER_INFO)) : null,
    uid: Cache.get(UID) || null,
};

const mutations = {
    LOGIN(state, opt) {
        state.token = opt.token;
        state.uid = opt.uid || null;
        Cache.set(LOGIN_STATUS, opt.token);
        if (opt.uid) Cache.set(UID, opt.uid);
    },
    SETUID(state, val) {
        state.uid = val;
        Cache.set(UID, val);
    },
    UPDATE_LOGIN(state, token) {
        state.token = token;
        Cache.set(LOGIN_STATUS, token);  // 添加缓存同步
    },
    LOGOUT(state) {
        state.token = '';  // 改为空字符串
        state.uid = null;  // 改为null
        state.userInfo = null;
        Cache.clear(LOGIN_STATUS);
        Cache.clear(UID);
        Cache.clear(USER_INFO);
    },
    UPDATE_USERINFO(state, userInfo) {
        state.userInfo = userInfo;
        Cache.set(USER_INFO, JSON.stringify(userInfo));  // 确保序列化
    }
};

const actions = {
    login({ commit }, payload) {
        commit('LOGIN', payload);
    },
    logout({ commit }) {
        commit('LOGOUT');
    },
    updateUserInfo({ commit }, userInfo) {
        commit('UPDATE_USERINFO', userInfo);
    }
};

export default {
    state,
    mutations,
    actions  // 添加actions
};